<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>编辑设备</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="cancel">返回</el-button>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="设备名称" prop="equipmentName">
          <el-input v-model="form.equipmentName" placeholder="请输入设备名称" />
        </el-form-item>

        <el-form-item label="设备编号" prop="equipmentCode">
          <el-input v-model="form.equipmentCode" placeholder="请输入设备编号" />
        </el-form-item>

        <el-form-item label="设备类型" prop="equipmentTypeId">
          <el-select v-model="form.equipmentTypeId" placeholder="请选择设备类型" clearable>
            <el-option
              v-for="item in equipmentTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="规格型号" prop="model">
          <el-input v-model="form.model" placeholder="请输入设备规格型号" />
        </el-form-item>

        <el-form-item label="设备状态" prop="equipmentStatus">
          <el-select v-model="form.equipmentStatus" placeholder="请选择设备状态">
            <el-option label="空闲" value="0" />
            <el-option label="在用" value="1" />
            <el-option label="维修中" value="2" />
            <el-option label="报废" value="3" />
          </el-select>
        </el-form-item>

        <el-form-item label="所属车间" prop="workshopId">
          <el-select 
            v-model="form.workshopId" 
            placeholder="请选择车间" 
            @change="handleWorkshopChange"
            @click.native="loadWorkshopOptions" 
            style="width: 100%"
          >
            <el-option
              v-for="item in workshopOptions"
              :key="item.workshop_id"
              :label="item.workshop_name"
              :value="item.workshop_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="所属生产线" prop="productionLineId">
          <el-select 
            v-model="form.productionLineId" 
            placeholder="请选择生产线" 
            @change="handleProductionLineChange"
            style="width: 100%"
          >
            <el-option
              v-for="item in productionLineOptions"
              :key="item.production_line_id"
              :label="item.production_line_name"
              :value="item.production_line_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="管理人" prop="responsiblePerson">
          <el-input 
            v-model="form.responsiblePerson" 
            placeholder="请选择管理人员" 
            readonly
            @click.native="openUserSelectDialog"
          >
            <el-button slot="append" icon="el-icon-user" @click.stop="openUserSelectDialog">选择</el-button>
          </el-input>
        </el-form-item>

        <el-form-item label="所属部门" prop="departmentName">
          <el-input 
            v-model="form.departmentName" 
            placeholder="选择管理人后自动填充"
            disabled
          />
        </el-form-item>

        <el-form-item label="购入日期" prop="purchaseDate">
          <el-date-picker
            v-model="form.purchaseDate"
            type="date"
            placeholder="选择购入日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>

        <el-form-item label="购入价格" prop="purchasePrice">
          <el-input-number v-model="form.purchasePrice" :precision="2" :step="1000" :min="0" controls-position="right" style="width: 100%;" />
        </el-form-item>

        <el-form-item label="厂商" prop="manufacturer">
          <el-input v-model="form.manufacturer" placeholder="请输入生产厂商" />
        </el-form-item>

        <el-form-item label="设备照片" prop="imageUrl">
          <el-upload
            class="avatar-uploader"
            action="#"
            name="avatarfile"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
            :http-request="uploadFile">
            <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户选择对话框 -->
    <el-dialog title="选择管理人员" :visible.sync="userSelectVisible" width="800px" append-to-body>
      <!-- 用户搜索表单 -->
      <el-form ref="userQueryForm" :model="userQueryParams" :inline="true">
        <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="userQueryParams.userName"
            placeholder="请输入用户名称"
            clearable
            size="small"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleUserQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="handleUserReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 用户列表 -->
      <el-table
        v-loading="userLoading"
        :data="userList"
        @row-click="selectUser"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="userName" label="用户名称" min-width="100" show-overflow-tooltip />
        <el-table-column prop="nickName" label="用户昵称" min-width="100" show-overflow-tooltip />
        <el-table-column prop="phonenumber" label="手机号码" min-width="120" show-overflow-tooltip />
        <el-table-column prop="dept.deptName" label="部门" min-width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.dept ? scope.row.dept.deptName : '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="80">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click.stop="selectUser(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="userTotal > 0"
        :total="userTotal"
        :page.sync="userQueryParams.pageNum"
        :limit.sync="userQueryParams.pageSize"
        @pagination="loadUserList"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getEquipment, updateEquipment, checkEquipmentCodeExcludeSelf } from '@/api/sb/equipmentLedger'
import { listUser } from "@/api/system/user";
import { listWorkshop } from "@/api/basic/factory";
import { getProductionLinesByWorkshop } from "@/api/basic/line";
import { uploadEquipmentImage } from "@/api/common/upload";
import Pagination from "@/components/Pagination";

export default {
  name: 'EditEquipment',
  components: { Pagination },
  data() {
    return {
      // 表单参数
      form: {
        equipmentId: undefined,
        equipmentName: '',
        equipmentCode: '',
        equipmentTypeId: null,
        equipmentTypeName: '',
        equipmentStatus: '0',
        model: '',
        specifications: '',
        workshopId: null,
        workshopName: '',
        productionLineId: null,
        productionLineName: '',
        departmentId: null,
        departmentName: '',
        responsiblePerson: '',
        userId: null,
        userNickName: '',
        purchaseDate: '',
        purchasePrice: '',
        manufacturer: '',
        imageUrl: '',
        remark: ''
      },
      // 保存原始设备编码，用于判断编码是否已修改
      originalEquipmentCode: '',
      // 设备类型选项
      equipmentTypeOptions: [],
      // 车间选项
      workshopOptions: [],
      // 生产线选项
      productionLineOptions: [],
      // 车间数据加载状态
      loadingWorkshops: false,
      // 生产线数据加载状态
      loadingProductionLines: false,
      // 上传文件列表
      fileList: [],
      // 用户选择对话框可见性
      userSelectVisible: false,
      // 用户加载状态
      userLoading: false,
      // 用户列表数据
      userList: [],
      // 用户总数
      userTotal: 0,
      // 用户查询参数
      userQueryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined
      },
      // 表单校验
      rules: {
        equipmentName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        equipmentCode: [
          { required: true, message: "设备编号不能为空", trigger: "blur" }
        ],
        equipmentTypeId: [
          { required: true, message: "请选择设备类型", trigger: "change" }
        ],
        equipmentStatus: [
          { required: true, message: "请选择设备状态", trigger: "change" }
        ],
        workshopId: [
          { required: true, message: "请选择所属车间", trigger: "change" }
        ],
        productionLineId: [
          { required: true, message: "请选择所属生产线", trigger: "change" }
        ],
        responsiblePerson: [
          { required: true, message: "请选择管理人", trigger: "change" }
        ]
      }
    }
  },
  created() {
    this.getEquipmentTypes();
    this.loadWorkshopOptions();
    const equipmentId = this.$route.params && this.$route.params.id;
    if (equipmentId) {
      this.getEquipmentInfo(equipmentId);
    }
  },
  methods: {
    /** 获取设备类型列表 */
    getEquipmentTypes() {
      // 模拟数据，实际应从后端获取
      this.equipmentTypeOptions = [
        { value: 1, label: '机械设备' },
        { value: 2, label: '电气设备' },
        { value: 3, label: '液压设备' },
        { value: 4, label: '气动设备' }
      ]
    },
    
    /** 加载车间选项 */
    loadWorkshopOptions() {
      if (this.loadingWorkshops) return;
      this.loadingWorkshops = true;
      listWorkshop({pageSize: 100, is_delete: 0}).then(response => {
        if (response.code === 200 && (response.rows || response.data)) {
          this.workshopOptions = response.rows || response.data;
        } else {
          this.workshopOptions = [];
        }
        this.loadingWorkshops = false;
      }).catch(error => {
        this.workshopOptions = [];
        this.loadingWorkshops = false;
      });
    },
    
    /** 处理车间变更 */
    handleWorkshopChange(value) {
      this.form.productionLineId = null; 
      this.form.productionLineName = '';
      this.productionLineOptions = [];
      if (!value) {
        this.form.workshopName = '';
        return;
      }
      const workshop = this.workshopOptions.find(item => item.workshop_id == value);
      if (workshop) {
        this.form.workshopName = workshop.workshop_name;
      }
      this.loadProductionLineOptions(value);
    },
    
    /** 加载生产线选项 */
    loadProductionLineOptions(workshopId) {
      if (!workshopId || this.loadingProductionLines) return;
      this.loadingProductionLines = true;
      getProductionLinesByWorkshop(workshopId).then(response => {
        if (response.code === 200 && (response.data || response.rows)) {
          this.productionLineOptions = response.data || response.rows;
        } else {
          this.productionLineOptions = [];
        }
        this.loadingProductionLines = false;
      }).catch(error => {
        this.productionLineOptions = [];
        this.loadingProductionLines = false;
      });
    },
    
    /** 处理生产线变更 */
    handleProductionLineChange(value) {
      const productionLine = this.productionLineOptions.find(item => item.production_line_id === value);
      if (productionLine) {
        this.form.productionLineName = productionLine.production_line_name;
        this.form.location = `${this.form.workshopName || ''}-${productionLine.production_line_name}`;
      }
    },
    
    /** 打开用户选择对话框 */
    openUserSelectDialog() {
      this.userSelectVisible = true;
      this.loadUserList();
    },
    
    /** 加载用户列表 */
    loadUserList() {
      this.userLoading = true;
      listUser(this.userQueryParams).then(response => {
        this.userLoading = false;
        if (response.code === 200) {
          this.userList = response.rows;
          this.userTotal = response.total;
        } else {
          this.userList = [];
          this.userTotal = 0;
          this.$message.error("获取用户列表失败: " + (response.msg || "未知错误"));
        }
      }).catch(error => {
        this.userLoading = false;
        console.error("获取用户列表错误:", error);
        this.$message.error("获取用户列表失败");
      });
    },
    
    /** 用户搜索 */
    handleUserQuery() {
      this.userQueryParams.pageNum = 1;
      this.loadUserList();
    },
    
    /** 用户重置查询 */
    handleUserReset() {
      this.$refs["userQueryForm"].resetFields();
      this.userQueryParams = {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined
      };
      this.loadUserList();
    },
    
    /** 选择用户 */
    selectUser(row) {
      this.form.userNickName = row.nickName; // 保存用户昵称
      this.form.responsiblePerson = row.nickName; // 展示用户昵称而不是用户名
      this.form.userId = row.userId; // 保存用户ID
      this.form.departmentName = row.dept ? row.dept.deptName : '';
      this.userSelectVisible = false;
      this.$message.success("已选择管理人员：" + row.nickName);
    },
    
    /** 获取设备信息 */
    getEquipmentInfo(equipmentId) {
      getEquipment(equipmentId).then(response => {
        this.form = response.data;
        // 确保equipmentId正确设置
        if (!this.form.equipmentId) {
          this.form.equipmentId = equipmentId;
        }
        console.log('获取到的设备信息:', this.form);
        this.originalEquipmentCode = this.form.equipmentCode; // 保存原始编码
        
        // 如果已有车间ID，加载对应的生产线
        if (this.form.workshopId) {
          this.loadProductionLineOptions(this.form.workshopId);
        }
        
        // 处理图片显示
        if (this.form.imageUrl) {
          this.fileList = [{ name: '设备图片', url: this.form.imageUrl }];
        }
      });
    },
    
    /** 文件上传前的检查 */
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    
    /** 处理文件上传 */
    uploadFile(options) {
      const { file, onSuccess, onError } = options;
      
      // 显示上传中提示
      this.$message.info('图片上传中...');
      
      console.log('编辑页面准备上传图片，参数名:', 'avatarfile');
      console.log('文件类型:', file.type);
      console.log('文件大小:', file.size);
      
      // 使用原生XHR上传文件，避开axios的默认处理
      const xhr = new XMLHttpRequest();
      const formData = new FormData();
      formData.append('avatarfile', file);
      
      // 获取token
      const token = this.$store.getters.token;
      
      xhr.open('POST', process.env.VUE_APP_BASE_API + '/ldzl-sb/sb/upload/image', true);
      xhr.setRequestHeader('Authorization', 'Bearer ' + token);
      
      xhr.onload = function() {
        if (xhr.status === 200) {
          try {
            const res = JSON.parse(xhr.responseText);
            console.log('图片上传响应:', res);
            
            if (res.code === 200) {
              // 尝试从多种可能的响应格式中提取URL
              let imageUrl = '';
              
              if (res.data && res.data.url) {
                imageUrl = res.data.url;
              } else if (res.url) {
                imageUrl = res.url;
              } else if (res.imgUrl) {
                imageUrl = res.imgUrl;
              } else if (res.data && typeof res.data === 'string') {
                imageUrl = res.data;
              } else if (res.data) {
                // 尝试从data对象中找到可能的URL字段
                const possibleFields = ['url', 'imgUrl', 'imageUrl', 'path', 'filePath', 'fileName'];
                for (const field of possibleFields) {
                  if (res.data[field]) {
                    imageUrl = res.data[field];
                    break;
                  }
                }
              }
              
              if (imageUrl) {
                // 确保图片URL是完整的URL路径
                if (imageUrl && !imageUrl.startsWith('http') && !imageUrl.startsWith('/')) {
                  imageUrl = process.env.VUE_APP_BASE_API + imageUrl;
                }
                
                onSuccess(res);
              } else {
                console.error('无法从响应中获取图片URL:', res);
                onError(new Error('无法获取图片URL'));
              }
            } else {
              console.error('图片上传失败:', res);
              onError(new Error(res.msg || '图片上传失败'));
            }
          } catch (e) {
            console.error('解析响应失败:', e);
            onError(e);
          }
        } else {
          console.error('图片上传请求失败:', xhr.status);
          onError(new Error('图片上传请求失败: ' + xhr.status));
        }
      };
      
      xhr.onerror = function() {
        console.error('上传文件请求错误');
        onError(new Error('上传文件请求错误'));
      };
      
      xhr.send(formData);
    },
    
    /** 上传成功处理 */
    handleUploadSuccess(res) {
      console.log("上传成功响应:", res);
      if (res && res.code === 200) {
        // 尝试从多种可能的响应格式中提取URL
        let imageUrl = '';
        
        if (res.data && res.data.url) {
          imageUrl = res.data.url;
        } else if (res.url) {
          imageUrl = res.url;
        } else if (res.imgUrl) {
          imageUrl = res.imgUrl;
        } else if (typeof res.data === 'string') {
          imageUrl = res.data;
        }
        
        if (imageUrl) {
          // 确保图片URL是完整的URL路径
          if (imageUrl && !imageUrl.startsWith('http') && !imageUrl.startsWith('/')) {
            imageUrl = process.env.VUE_APP_BASE_API + imageUrl;
          }
          
          this.form.imageUrl = imageUrl;
          this.$message.success('图片上传成功');
        } else {
          this.$message.error('无法获取上传的图片URL');
          console.error('无法从响应中获取图片URL:', res);
        }
      } else {
        this.$message.error(res.msg || "上传失败");
      }
    },
    
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log('准备提交表单数据:', JSON.stringify(this.form));
          
          // 检查设备编码是否已修改
          if (this.form.equipmentCode !== this.originalEquipmentCode) {
            console.log('设备编码已修改，检查是否重复');
            checkEquipmentCodeExcludeSelf(this.form.equipmentCode, this.form.equipmentId).then(response => {
              console.log('排除自身的编码检查结果:', response);
              const codeExists = response.data === true;
              if (response.code === 200 && !codeExists) {
                console.log('编码可用，提交更新');
                this.doUpdateEquipment();
              } else {
                this.$modal.msgError("设备编码已存在，请重新输入");
              }
            }).catch(error => {
              console.error("检查设备编码错误:", error);
              this.$modal.msgError("检查设备编码失败，请稍后重试");
            });
          } else {
            console.log('设备编码未修改，直接提交更新');
            this.doUpdateEquipment();
          }
        }
      });
    },
    
    /** 执行更新操作 */
    doUpdateEquipment() {
      // 确保表单中设备ID字段名是equipmentId而不是id
      if (!this.form.equipmentId && this.$route.params && this.$route.params.id) {
        this.form.equipmentId = Number(this.$route.params.id);
        console.log('从路由参数设置equipmentId:', this.form.equipmentId);
      }
      
      console.log('提交更新设备数据:', this.form);
          updateEquipment(this.form).then(response => {
        console.log('更新成功响应:', response);
            this.$modal.msgSuccess("修改成功");
            this.cancel();
      }).catch(error => {
        console.error("修改设备错误:", error);
        let errorMsg = error.response && error.response.data ? error.response.data.message : "修改失败，请稍后重试";
        this.$modal.msgError(errorMsg);
      });
    },
    
    /** 取消按钮 */
    cancel() {
      this.$router.push({ path: "/sb/equipment-ledger" });
    }
  }
}
</script> 

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
}
.avatar {
  width: 128px;
  height: 128px;
  display: block;
}
</style> 